package com.totoro.mall.mall_buyer.controller;

import com.totoro.mall.mall_buyer.enums.ResultEnum;
import com.totoro.mall.mall_buyer.exception.SellException;
import com.totoro.mall.mall_buyer.from.CategoryForm;
import com.totoro.mall.mall_buyer.model.ProductCategory;
import com.totoro.mall.mall_buyer.service.IProductCategoryService;
import com.totoro.mall.mall_buyer.utils.ResultVOUtil;
import com.totoro.mall.mall_buyer.vo.PageDataVO;
import com.totoro.mall.mall_buyer.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 卖家商品目录
 * Created by Niki on 2018/4/12 8:29
 */
@RestController
@RequestMapping("/sell/category")
public class SellCategoryController {

    @Resource
    IProductCategoryService productCategoryService;

    /**
     * 展示单个目录详情
     * @param categoryId
     * @return
     */
    @GetMapping("/index/{categoryId}")
    public ResultVO<ProductCategory> index(@PathVariable Integer categoryId) throws SellException {
        if (categoryId == null) {
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        ProductCategory category = productCategoryService.findById(categoryId);
        return ResultVOUtil.success(category);
    }

    @GetMapping("/list/{page}/{size}")
    public ResultVO<List<ProductCategory>> list(@PathVariable Integer page, @PathVariable Integer size){
        if(page == null){
            page = 0;
        }
        if (size == null) {
            size = 20;
        }

        Page<ProductCategory> listPage = productCategoryService.findByPage(page, size);

        int total = listPage.getTotalPages();
        List<ProductCategory> productCategoryList = listPage.getContent();
        PageDataVO data = new PageDataVO(page,size , total, productCategoryList);
        return ResultVOUtil.success(data);
    }


    /**
     * 保存/修改目录
     * @param from
     * @return
     */
    @PostMapping("/save")
    public ResultVO<ProductCategory> save(@RequestBody CategoryForm from){
        Integer categoryId = from.getCategoryId();
        ProductCategory category = new ProductCategory();
        if(categoryId != null){
            category = productCategoryService.findById(categoryId);
        }
        // TODO: 2018/4/12 BeanUtils耗时较长，改成自己的方法来转换Bean
        BeanUtils.copyProperties(from, category);
        productCategoryService.save(category);

        return ResultVOUtil.success(category);
    }



}
